package com.studyroom.controller;

import com.studyroom.common.Result;
import com.studyroom.dto.TimeRangeDTO;
import com.studyroom.entity.StudyRoom;
import com.studyroom.entity.Seat;
import com.studyroom.service.StudyRoomService;
import com.studyroom.service.SeatService;
import com.studyroom.vo.SeatAvailabilityVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/admin/study-rooms")
public class StudyRoomController {

    @Autowired
    private StudyRoomService studyRoomService;

    @Autowired
    private SeatService seatService;

    @GetMapping
    public Result<List<StudyRoom>> listAll() {
        return Result.success(studyRoomService.list());
    }

    @GetMapping("/list")
    public Result<?> list() {
        List<StudyRoom> rooms = studyRoomService.list();
        return Result.success(rooms);
    }

    @GetMapping("/{id}")
    public Result<StudyRoom> getById(@PathVariable Long id) {
        return Result.success(studyRoomService.getById(id));
    }

    @PostMapping
    public Result<?> add(@RequestBody StudyRoom studyRoom) {
        studyRoomService.save(studyRoom);
        return Result.success();
    }

    @PutMapping("/{id}")
    public Result<?> update(@PathVariable Long id, @RequestBody StudyRoom studyRoom) {
        studyRoom.setId(id);
        studyRoomService.updateById(studyRoom);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable Long id) {
        StudyRoom studyRoom = studyRoomService.getById(id);
        if (studyRoom == null) {
            return Result.error("自习室不存在");
        }
        
        studyRoom.setIsDeleted(1);
        studyRoomService.updateById(studyRoom);
        return Result.success();
    }

    @GetMapping("/{roomId}/seats")
    public Result<List<Seat>> getSeats(@PathVariable Long roomId) {
        return Result.success(seatService.getByRoomId(roomId));
    }

    @PutMapping("/{roomId}/seats/{seatId}")
    public Result<?> updateSeatStatus(
            @PathVariable Long roomId,
            @PathVariable Long seatId,
            @RequestBody Seat seat) {
        seat.setId(seatId);
        seat.setRoomId(roomId);
        seatService.updateById(seat);
        return Result.success();
    }

    @PostMapping("/{roomId}/seats/availability")
    public Result getSeatAvailability(
        @PathVariable Long roomId,
        @RequestBody TimeRangeDTO timeRange
    ) {
        List<SeatAvailabilityVO> seats = studyRoomService.getSeatAvailability(
            roomId, 
            timeRange.getStartTime(), 
            timeRange.getEndTime()
        );
        return Result.success(seats);
    }
} 